<script setup lang="ts">
import { computed, ref } from "vue";
import { handleJsonData } from "@/components/SmartForm/utils";
import Detail from "./Detail.vue";
interface Props {
  modelValue?: string;
  mode: API.Form.Mode;
  controlAttr: API.Form.ControlAttrItem;
}
const props = defineProps<Props>();

const visible = ref(false);
const dataConfig = computed(() => props.controlAttr.dataConfig);
const columns = computed(() => {
  switch (dataConfig.value?.type) {
    case "custom":
      return dataConfig.value.options ?? [];

    default:
      return [];
  }
});
console.log(columns, "columns");

const emit = defineEmits(["update:modelValue"]);
const onChange = (value: string | undefined) =>
  emit("update:modelValue", value);
const onConfirm = (_value: string, index: number) => {
  const result = {
    ...dataConfig.value?.options[index],
  };
  onChange(JSON.stringify(result));
  visible.value = false;
};
const selectValue = computed(() => {
  return handleJsonData(props.modelValue ?? "{}") as {
    label: string;
    value: string | number;
  };
});
</script>

<template>
  <van-field
    v-if="mode === 'edit'"
    readonly
    right-icon="arrow"
    class="clear-field"
    :placeholder="controlAttr.placeholder"
    :model-value="selectValue.label"
    @click="visible = true"
  ></van-field>
  <van-popup v-model:show="visible" round position="bottom">
    <van-picker
      :columns="columns"
      @cancel="visible = false"
      :columns-field-names="{ text: 'label' }"
      @confirm="onConfirm"
      item-height="1.17333rem"
    />
  </van-popup>
  <Detail v-if="mode === 'read'" :value="selectValue.label" />
</template>

<style scoped lang="scss"></style>
